﻿using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace AESUtil
{
    public class RequestItem
    {
        public string Name { get; set; }
        public string requestStr { get; set; }
        public string resultStr { get; set; }

    }
    internal class RequestHistoryUtil
    {
        private static string fileName = "RequestHistory.txt";
        public static void saveToFile(RequestItem item)
        {
            try
            {
                String filePath = fileName;
                List<RequestItem> oldList;
                if (File.Exists(filePath))
                {
                    // 1. 从文件读取 JSON 字符串
                    string jsonStringFromFile = File.ReadAllText(filePath);
                    // 2. 反序列化 JSON 字符串为对象
                    oldList = JsonConvert.DeserializeObject<List<RequestItem>>(jsonStringFromFile);
                }
                else
                {
                    oldList = new List<RequestItem>();
                }


                oldList.Add(item);
                string jsonString = JsonConvert.SerializeObject(oldList, Formatting.Indented);

                // 2. 将 JSON 字符串写入文件
                File.WriteAllText(filePath, jsonString);
            }
            catch (Exception)
            {
                throw;
            }
        }
        public static List<RequestItem> getHistory()
        {
            String filePath = fileName;
            List<RequestItem> oldList;
            if (File.Exists(filePath))
            {
                // 1. 从文件读取 JSON 字符串
                string jsonStringFromFile = File.ReadAllText(filePath);

                // 2. 反序列化 JSON 字符串为对象
                oldList = JsonConvert.DeserializeObject<List<RequestItem>>(jsonStringFromFile);
            }
            else
            {
                oldList = new List<RequestItem>();
            }
            return oldList;
        }
        public static void clearHistory()
        {
            String filePath = fileName;
            if (File.Exists(filePath))
            {
                File.WriteAllText(filePath, "[]");
            }
        }
        public static void updateHistory(List<RequestItem> newList)
        {
            String filePath = fileName;
            string jsonString = JsonConvert.SerializeObject(newList, Formatting.Indented);

            File.WriteAllText(filePath, jsonString);
        }
    }
}
